package com.szeastroc.manage.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.szeastroc.core.bean.system.SystemResource;
import com.szeastroc.core.bean.system.SystemRole;
import com.szeastroc.core.bean.system.SystemUser;
import com.szeastroc.core.service.system.SystemUserService;

@Configuration
public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private SystemUserService systemUserService;


	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
		SystemUser systemUser = (SystemUser) principals.getPrimaryPrincipal();  
		for (SystemRole role : systemUser.getRoles()) {  
			authorizationInfo.addRole(role.getName());  			
		}  
		for (SystemRole role : systemUser.getRoles()) {
			for (SystemResource resource : role.getSysytemResources()) {
				authorizationInfo.addStringPermission(resource.getPermission());
			}
		}
		return authorizationInfo;  
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();   
      //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法  
	  SystemUser systemUser = systemUserService.selectByUserName(username);
      if (systemUser == null) {  
          return null;  
      }  
      if (systemUser.getStatus() == 0) { //账户冻结  
          throw new LockedAccountException();  
      }  
      SecurityUtils.getSubject().getSession().setAttribute("user", systemUser);
      SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(  
    		  systemUser.getName(), //用户名  
    		  systemUser.getPassword(), //密码  
              getName()  //realm name  
      );  
      return authenticationInfo;  
	}

}
